﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MkvSplicer.Video
{
    public abstract class SplitInfo
    {
        public readonly long splitStart, splitEnd;
        public readonly long innerStart, innerEnd;
        public readonly long outerStart;

        public bool StartIsKeyFrame { get { return splitStart == outerStart; } }
        public bool EndIsKeyFrame { get { return splitEnd == innerEnd; } }

        private VideoTrack parent;

        protected SplitInfo(VideoTrack parent, string timeStart, string timeEnd)
        {
            this.parent = parent;
            splitStart = parent.ConvertToFrameNumber(timeStart);
            splitEnd = parent.ConvertToFrameNumber(timeEnd);
            if (splitEnd <= splitStart)
                throw new FormatException("Invalid split range");
            innerStart = parent.FindNearestKeyframe(splitStart, false);
            innerEnd = parent.FindNearestKeyframe(splitEnd, true);
            outerStart = parent.FindNearestKeyframe(splitStart, true);
        }

        protected SplitInfo(VideoTrack parent, long frameStart, long frameEnd)
        {
            this.parent = parent;
            splitStart = frameStart;
            splitEnd = frameEnd;
            if (splitStart < 0 || splitEnd < 0 || splitEnd <= splitStart)
                throw new FormatException("Invalid split range");
            innerStart = parent.FindNearestKeyframe(splitStart, false);
            innerEnd = parent.FindNearestKeyframe(splitEnd, true);
            outerStart = parent.FindNearestKeyframe(splitStart, true);
            if (innerStart > innerEnd)
                innerStart = innerEnd;
        }

        public override string ToString()
        {
            return String.Format("Start: {0} ({1}), End: {2} ({3}), KeyStart: {4}, KeyEnd: {5}",
                splitStart, Timecodes.FormatTime(parent.ConvertFrameNumberToTimecode(splitStart)), 
                splitEnd, Timecodes.FormatTime(parent.ConvertFrameNumberToTimecode(splitEnd)),
                innerStart, innerEnd);
        }
    }
}
